package com.example.jedis.demo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Set;

/**
 * 描述该类
 *
 * @author <a href="920786312@qq.com">周飞</a>
 * @class: Demo01
 * @date 2022/2/2  15:23
 * @Verson 1.0 -2022/2/2  15:23
 * @see
 */
public class Demo03 {
    public static void main(String[] args) {
        Jedis jedis =getJedisFromSentinel();

        jedis.set("k1", "v1");
        System.out.println("哨兵测试:" + jedis.get("k1"));
        jedis.close();
    }

    private static JedisSentinelPool jedisSentinelPool=null;

    public static  Jedis getJedisFromSentinel(){
        if(jedisSentinelPool==null){
            //redis主从机器访问密码
            String password="123456";
            //哨兵配置
            Set<String> sentinelSet=new HashSet<>();
            sentinelSet.add("192.168.187.139:26379");
            sentinelSet.add("192.168.187.138:26380");
            sentinelSet.add("192.168.187.138:26381");

            JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(10); //最大可用连接数
            jedisPoolConfig.setMaxIdle(5); //最大闲置连接数
            jedisPoolConfig.setMinIdle(5); //最小闲置连接数
            jedisPoolConfig.setBlockWhenExhausted(true); //连接耗尽是否等待
            jedisPoolConfig.setMaxWaitMillis(2000); //等待时间
            jedisPoolConfig.setTestOnBorrow(true); //取连接的时候进行一下测试 ping pong

            jedisSentinelPool=new JedisSentinelPool("appmaster",sentinelSet,jedisPoolConfig,password);
            return jedisSentinelPool.getResource();
        }else{
            return jedisSentinelPool.getResource();
        }
    }
}